// pages/debug-token/debug-token.js - 调试特定token
Page({
  data: {
    result: ''
  },

  onLoad() {
    const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiLlvq7kv6HnlKjmiLciLCJ1c2VySWQiOiIxOTY5NzgxNzA2MjQxNzgxNzYxIiwiaWF0IjoxNzU4NDY3NTMwLCJleHAiOjE3NTg1NTM5MzB9.r99zMy079nWBkazKSRasDRgU8xqsU_x0VrtNz58Z8HU";
    
    this.debugSpecificToken(token);
  },

  debugSpecificToken(token) {
    let result = '=== 调试特定Token ===\n\n';
    
    try {
      result += `Token: ${token}\n\n`;
      
      const parts = token.split('.');
      result += `Token部分: ${parts.length}\n`;
      
      if (parts.length === 3) {
        // 解析Header
        const header = parts[0];
        result += `\n1. Header部分: ${header}\n`;
        try {
          const headerDecoded = this.base64UrlDecode(header);
          result += `Header解码: ${headerDecoded}\n`;
          const headerObj = JSON.parse(headerDecoded);
          result += `Header解析: ${JSON.stringify(headerObj, null, 2)}\n`;
        } catch (e) {
          result += `Header解析失败: ${e.message}\n`;
        }
        
        // 解析Payload
        const payload = parts[1];
        result += `\n2. Payload部分: ${payload}\n`;
        try {
          const payloadDecoded = this.base64UrlDecode(payload);
          result += `Payload解码: ${payloadDecoded}\n`;
          
          // 尝试解析JSON
          const payloadObj = JSON.parse(payloadDecoded);
          result += `Payload解析成功: ${JSON.stringify(payloadObj, null, 2)}\n`;
          
          // 提取用户ID
          const userId = payloadObj.userId || payloadObj.sub || payloadObj.id;
          result += `提取的用户ID: ${userId}\n`;
          
        } catch (e) {
          result += `Payload解析失败: ${e.message}\n`;
          
          // 尝试使用不同的解码方式
          try {
            const altDecoded = this.alternativeBase64Decode(payload);
            result += `备用解码方式结果: ${altDecoded}\n`;
          } catch (e2) {
            result += `备用解码也失败: ${e2.message}\n`;
          }
        }
        
        // 解析Signature
        const signature = parts[2];
        result += `\n3. Signature部分: ${signature}\n`;
      }
      
    } catch (error) {
      result += `整体解析失败: ${error.message}\n`;
    }
    
    this.setData({ result });
  },

  // Base64 URL解码 (JWT标准)
  base64UrlDecode(str) {
    // 将Base64 URL转换为标准Base64
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    
    // 添加padding
    const pad = str.length % 4;
    if (pad) {
      if (pad === 1) {
        throw new Error('Invalid Base64 string');
      }
      str += new Array(5 - pad).join('=');
    }
    
    return this.base64Decode(str);
  },

  // Base64解码函数
  base64Decode(input) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    let str = input.replace(/[=]+$/, '');
    let output = '';
    
    if (str.length % 4 === 1) {
      throw new Error('Invalid Base64 input length');
    }
    
    for (let bc = 0, bs = 0, buffer, i = 0; str.charAt(i) || (buffer = '=', i % 4); output += String.fromCharCode(255 & buffer >> (-2 * i & 6))) {
      buffer = chars.indexOf(str.charAt(i++));
      if (buffer === -1) {
        throw new Error('Invalid Base64 character at position ' + (i-1));
      }
      buffer = bc % 4 ? buffer * 64 + bs : buffer;
      bs = bc++ % 4 ? bs : buffer;
    }
    
    return output;
  },

  // 备用Base64解码方式
  alternativeBase64Decode(input) {
    // 使用小程序的内置方法(如果有的话)
    if (typeof wx.base64ToArrayBuffer === 'function') {
      try {
        const buffer = wx.base64ToArrayBuffer(input);
        return String.fromCharCode.apply(null, new Uint8Array(buffer));
      } catch (e) {
        throw new Error('wx.base64ToArrayBuffer failed: ' + e.message);
      }
    }
    
    throw new Error('No alternative decode method available');
  },

  copyResult() {
    wx.setClipboardData({
      data: this.data.result,
      success() {
        wx.showToast({ title: '已复制', icon: 'success' });
      }
    });
  }
});
